<template>
  <div class="main">
    <mine-title>新建前沿算法</mine-title>
    <div class="content" v-loading="loading">
      <mine-steps class="steps" :active="stepActive">
        <mine-step
          v-for="(item, index) in steps"
          :key="index"
          :title="item.name"
        ></mine-step>
      </mine-steps>
      <!-- 填写信息 -->
      <div class="flex-center">
        <div v-if="stepActive === 0">
          <div class="form-limit">
            <el-form
              ref="form"
              :model="form"
              :rules="rules"
              label-width="100px"
            >
              <el-form-item label="算法类型：" prop="projectType">
                <el-radio-group v-model="form.projectType">
                  <el-radio
                    v-for="(item, index) in projectTypeList"
                    :key="index"
                    :label="item.id"
                    >{{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="算法名称：" prop="projectName">
                <el-input
                  v-model="form.projectName"
                  placeholder="请输入算法名称"
                  clearable
                  size="small"
                />
              </el-form-item>
              <el-form-item label="模型描述：" prop="projectDesc">
                <el-input
                  type="textarea"
                  v-model.trim="form.projectDesc"
                  :autosize="{ minRows: 5, maxRows: 10 }"
                  placeholder="请输入模型描述"
                  showMaxLimit
                  :maxlength="200"
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div style="text-align: center">
            <el-radio-group
              class="actionType"
              v-model="actionType"
              size="small"
            >
              <el-radio-button label="upload">文件上传</el-radio-button>
              <el-radio-button label="select">我的数据集</el-radio-button>
            </el-radio-group>
          </div>
          <div v-show="actionType === 'upload'">
            <newDataList
              ref="newDataList"
              :projectType.sync="form.projectType"
            />
          </div>
          <div v-show="actionType === 'select'">
            <selectDataList
              ref="selectDataList"
              :projectType.sync="form.projectType"
              @getModelTableData="getModelTableData"
            />
          </div>
          <div class="form-btn-row is-center">
            <mine-button type="primary" secondary @click="prev0"
              >返 回</mine-button
            >
            <mine-button type="primary" @click="next0"
              >下一步，算法裁剪</mine-button
            >
          </div>
        </div>
        <!-- 代码裁剪 -->
        <div v-if="stepActive === 1">
          <div class="form-btn-row is-center">
            <el-form
              ref="codeCutForm"
              :model="codeCutform"
              :rules="codeCutform.rules"
            >
              <el-table
                class="table border-table"
                :data="codeCutform.tableData"
                style="width: 100%"
                ref="multipleTable"
                @selection-change="codeCutCheckboxSelection"
              >
                <!-- v-loading="loading"
                    :height="tableHeight" -->
                <el-table-column type="selection" show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                  prop="dirName"
                  label="名称"
                  width="380px"
                  show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                  prop="parameters"
                  label="参数"
                  show-overflow-tooltip
                  width="400px"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'tableData[' + scope.$index + '].parameters'"
                      :rules="
                        codeCutSelected.length &&
                        codeCutSelected.indexOf(scope.row) !== -1
                          ? codeCutform.rules.parameters
                          : []
                      "
                    >
                      <el-select
                        v-model="scope.row.parameters"
                        placeholder="请选择"
                        clearable
                      >
                        <el-option
                          v-for="item in scope.row.childrenParams"
                          :key="item.id"
                          :label="item.optName"
                          :value="item.optName"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <mine-button type="primary" secondary @click="prev5"
              >返 回</mine-button
            >
            <mine-button type="primary" @click="next5"
              >下一步，训练模型</mine-button
            >
          </div>
        </div>
        <!-- 训练模型 -->
        <div class="form-wrapper flex-center" v-if="stepActive === 2">
          <div class="form-limit">
            <el-form
              ref="trainForm"
              :model="trainFormData"
              :rules="trainFormRules"
              label-width="110px"
            >
              <el-form-item
                label="算法模型："
                prop="algorithmClass"
                key="algorithmClass"
              >
                <el-select
                  v-model="trainFormData.algorithmClass"
                  size="small"
                  clearable
                  @change="changeAlgorithmClass"
                >
                  <el-option
                    v-for="(item, i) in algorithmClassList"
                    :key="i"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="任务类型：" prop="taskType" key="taskType">
                <el-select
                  v-model="trainFormData.taskType"
                  size="small"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in taskTypeList"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="选择算法："
                prop="algorithmName"
                key="algorithmName"
                v-if="trainFormData.taskType === '1'"
                required
              >
                <el-select
                  v-model="trainFormData.algorithmName"
                  size="small"
                  clearable
                  @change="changeAlgorithm"
                >
                  <el-option
                    v-for="(item, i) in algorithmSelect"
                    :key="i"
                    :label="item.algorithmName"
                    :value="item.algorithmName"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="算法参数："
                prop="extraParam"
                key="extraParam"
                v-if="trainFormData.taskType === '1'"
              >
                <el-input
                  type="textarea"
                  v-model="trainFormData.extraParam"
                  :autosize="{ minRows: 2, maxRows: 5 }"
                  placeholder="请输入算法参数"
                  showMaxLimit
                ></el-input>
              </el-form-item>
              <!-- 无监督学习，训练集占比不显示，默认传0.8，[from bug-view-4452.html] -->
              <el-form-item
                v-if="!['data_unsupervised'].includes(form.projectType)"
                label="训练集占比："
                prop="proportion"
                key="proportion"
              >
                <el-select
                  v-model="trainFormData.proportion"
                  size="small"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in proportionList"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- 还有当算法类型选择“聚类”和“关联规则”时，去掉标签列 -->
              <el-form-item label="选择数据集：" :required="true">
                <div class="data-set">
                  <img :src="fileIcon" />
                  <div>
                    <el-tooltip
                      effect="dark"
                      :content="trainFormData.fileName"
                      placement="top-start"
                    >
                      <div class="data-set-title">
                        {{ this.$common.cutText(trainFormData.fileName, 15) }}
                      </div>
                    </el-tooltip>
                    <mine-button
                      v-if="
                        [
                          'data_predict',
                          'txt_classify',
                          'data_unsupervised',
                        ].includes(form.projectType)
                      "
                      type="primary"
                      secondary
                      size="mini"
                      @click="setShowViewFile"
                    >
                      预览数据
                    </mine-button>
                  </div>
                </div>
              </el-form-item>
              <el-form-item
                label="数据预览："
                key="viewFile"
                v-if="
                  [
                    'data_predict',
                    'txt_classify',
                    'data_unsupervised',
                  ].includes(form.projectType)
                "
              >
                <viewFileTable :viewFile="viewFile"></viewFileTable>
              </el-form-item>
              <el-form-item
                label="标签列："
                prop="targetColumn"
                key="targetColumn"
                v-if="
                  ['data_predict', 'txt_classify'].includes(form.projectType) &&
                  ['聚类', '关联规则'].indexOf(trainFormData.algorithmClass) ===
                    -1
                "
              >
                <el-select
                  v-model="trainFormData.targetColumn"
                  size="small"
                  clearable
                  :disabled="!targetList.length"
                >
                  <el-option
                    v-for="(item, i) in targetList"
                    :key="i"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="自变量："
                prop="variableName"
                key="variableName"
                v-if="
                  [
                    'data_predict',
                    'data_unsupervised',
                    'txt_classify',
                  ].includes(form.projectType)
                "
              >
                <el-select
                  v-model="trainFormData.variableName"
                  multiple
                  collapse-tags
                  size="small"
                  clearable
                  :disabled="!variablefilterList.length"
                >
                  <el-option
                    v-for="(item, i) in variablefilterList"
                    :key="i"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <div class="form-btn-row is-center">
            <mine-button type="primary" secondary @click="prev2"
              >上一步</mine-button
            >
            <mine-button type="primary" @click="next2"
              >下一步，开始训练</mine-button
            >
          </div>
        </div>
        <!-- 发布 -->
        <div v-if="stepActive === 3">
          <div class="form-wrapper is-center">
            <div v-show="resultStatus === 'success'">
              <div class="progress-item is-success">
                <el-progress
                  class="progress"
                  type="circle"
                  :percentage="100"
                  :width="progressWidth"
                  :stroke-width="strokeWidth"
                  status="success"
                ></el-progress>
                <p class="progress-text">模型训练完成</p>
                <p
                  class="progress-tips"
                  style="font-weight: 700; font-size: 20px; color: red"
                  v-if="successMessage"
                >
                  {{ successMessage }}
                </p>
              </div>
              <p>模型评估结果</p>
              <modelResults :data-list="modelResults" />
              <div class="form-btn-row is-center" style="margin-top: 42px">
                <mine-button type="primary" secondary @click="goBack"
                  >返回模型详情
                </mine-button>
                <mine-button
                  type="primary"
                  @click="publish"
                  v-if="
                    statusUnpublish(modelData) &&
                    form.projectType !== 'data_unsupervised'
                  "
                >
                  发布模型
                </mine-button>
              </div>
            </div>
            <div v-show="resultStatus === 'error'">
              <div class="progress-item is-error">
                <el-progress
                  class="progress"
                  type="circle"
                  :percentage="100"
                  :width="progressWidth"
                  :stroke-width="strokeWidth"
                  status="exception"
                ></el-progress>
                <p class="progress-text">模型训练失败</p>
                <p class="progress-tips">失败原因：{{ errorMessage }}</p>
                <div class="form-btn-row is-center">
                  <mine-button type="primary" secondary @click="goBackList">
                    返回模型列表
                  </mine-button>
                  <!-- <mine-button type="primary" @click="next2">重新训练</mine-button> -->
                </div>
              </div>
            </div>
            <div v-show="resultStatus === 'default'">
              <div class="progress-item is-default">
                <el-progress
                  class="progress"
                  type="circle"
                  :percentage="75"
                  :width="progressWidth"
                  :stroke-width="strokeWidth"
                ></el-progress>
                <p class="progress-text">模型训练中…</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mappingMixins } from "../mixins";
import newDataList from "./newDataList";
import selectDataList from "./selectDataList";
import modelResults from "./modelResults";
import viewFileTable from "./viewFileTable";
import _ from "lodash";
import isJSON from "@/utils/is-json";
import { doChildComponentSubmit } from "../../../../../utils/common";
import { resolve } from "@antv/x6/lib/registry/router/manhattan/options";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";
import { isArray } from "@antv/x6/lib/util/lang/lang";

export default {
  mixins: [mappingMixins],
  components: {
    newDataList,
    selectDataList,
    modelResults,
    viewFileTable,
  },
  computed: {
    projectTypeList() {
      return [
        {
          id: "data_predict",
          name: "数据诊断",
        },
        {
          id: "data_unsupervised",
          name: "无监督学习",
        },
      ];
      //   this.classifyList.filter((item) => item.id !== "other");
    },
    algorithmClassList() {
      let algorithmList = _.cloneDeep(this.algorithmList),
        result = [];
      if (algorithmList.length === 0) {
        return result;
      }
      result = _.keys(_.groupBy(algorithmList, "algorithmClass"));
      let res = result.slice(0, 1);
      // 设置默认值
      if (!this.trainFormData.algorithmClass && res[0]) {
        this.$set(this.trainFormData, "algorithmClass", res[0]);
        this.$set(
          this.trainFormData,
          "type",
          this.algorithmSelect[0].algorithmType
        );
      }
      return res;
    },
    algorithmSelect() {
      let algorithmList = _.cloneDeep(this.algorithmList),
        result = [],
        algorithmClass = this.trainFormData.algorithmClass;
      if (algorithmList.length === 0) {
        return result;
      }
      if (!algorithmClass) {
        return result;
      }
      result = _.filter(algorithmList, {
        algorithmClass: algorithmClass,
      });
      // 设置默认值
      this.$set(this.trainFormData, "algorithmName", result[0].algorithmName);
      return result;
    },
    variablefilterList() {
      let result = [],
        variableList = this.variableList,
        targetColumn = this.trainFormData.targetColumn;
      result = _.filter(variableList, (value) => {
        return value !== targetColumn;
      });
      return result;
    },
  },
  data() {
    return {
      fileIcon: require("@/assets/img/file.svg"),
      loading: false,
      stepActive: 0,
      steps: [
        { id: 0, name: "创建模型" },
        { id: 1, name: "算法裁剪" },
        // {id: 1, name: '选择数据集'},
        { id: 2, name: "训练模型" },
        { id: 3, name: "发布" },
      ],
      form1: {
        id: "",
        creater: this.$store.state.userName,
        projectType: "txt_classify", // 文本分类模式
        projectName: "文本01",
        projectDesc: "文本文本",
        isAvailable: true,
        diagnoseType: 1,
      },
      form: {
        id: "",
        creater: this.$store.state.userName,
        projectType: "data_predict",
        projectName: "",
        projectDesc: "",
        isAvailable: true,
        diagnoseType: 1,
      },
      rules: {
        projectType: {
          required: true,
          message: "请选择算法类型",
          trigger: "change",
        },
        projectName: {
          required: true,
          message: "请输入算法名称",
          trigger: "blur",
        },
        projectDesc: {
          required: true,
          message: "请输入模型描述",
          trigger: "blur",
        },
      },
      trainFormRules: {
        targetColumn: [
          {
            required: true,
            message: "请选择标签列",
            trigger: "change",
          },
          { validator: this.validateTarget, trigger: "change" },
        ],
        variableName: [
          {
            required: false,
            message: "请选择自变量",
            trigger: "change",
          },
          // { validator: this.validateVariable, trigger: 'change' }
        ],
        algorithmClass: [
          {
            required: true,
            message: "请选择算法模型",
            trigger: "change",
          },
        ],
        taskType: [{ required: true, message: "任务类型", trigger: "change" }],
        algorithmName: [
          {
            required: false,
            message: "请选择算法",
            trigger: "change",
          },
        ],
        proportion: [
          {
            required: true,
            message: "请选择训练集占比",
            trigger: "change",
          },
        ],
        extraParam: [
          {
            required: true,
            validator: this.checkExtraParam,
            trigger: ["blur", "change"],
          },
        ],
      },
      hasSelectFile: false,
      actionType: "upload",
      trainFormData: {
        id: "",
        fileId: "",
        fileName: "",
        targetColumn: "",
        variableName: [],
        algorithmName: "",
        algorithmClass: "",
        taskType: "1",
        proportion: "0.7",
        type: "",
        projectId: "",
        extraParam: "",
      },
      materialFormData: {
        id: "",
        fileDesc: "",
        fileName: "",
        fileType: "",
        file: "",
      },
      showViewFile: false,
      viewFile: [],
      algorithmList: [],
      targetList: [],
      modelData: {},
      modelResults: [],
      variableList: [],
      taskTypeList: [
        { id: "1", name: "自选" },
        { id: "2", name: "自动" },
      ],
      proportionList: [
        { id: "0.5", name: "50%" },
        { id: "0.6", name: "60%" },
        { id: "0.7", name: "70%" },
        { id: "0.8", name: "80%" },
        { id: "0.9", name: "90%" },
      ],
      strokeWidth: 8,
      progressWidth: 96,
      resultStatus: "default", // success: 成功, error: 失败, default: 运行中
      errorMessage: "",
      // 代码裁剪中的表格表格
      codeCutform: {
        tableData: {},
        rules: { parameters: [{ required: true, message: "请选择" }] },
      },
      codeCutSelected: [], // 代码裁剪选中的项

      // uuid List
      loadAlgorithmUUID: "",
      creatModalUUID: "",
      uploadFileUUID: "",
      saveDataAndUploadUUID: "",
      successMessage: "", // 成功状态下备注
      apiCount: 0, // 训练接口递归调用计数
    };
  },
  watch: {
    algorithmList(newValue, oldValue) {
      if (newValue.length === 0) {
        return;
      }
      if (this.trainFormData.id) {
        const target = _.find(newValue, {
          algorithmType: this.trainFormData.type,
        });
        if (target) this.trainFormData.algorithmClass = target.algorithmClass;
      }
    },
    stepActive(newValue, oldValue) {
      if (newValue === 1) {
        //  进入模型训练环节，加载算法信息
        setTimeout(() => {
          this.loadAlgorithm();
        }, 1000);
      }
    },
    "trainFormData.algorithmClass"(newValue) {
      this.setDefaultParameter();
    },
    "trainFormData.algorithmName"(newValue) {
      this.setDefaultParameter();
    },
  },
  methods: {
    // 代码裁剪中复选框事件
    codeCutCheckboxSelection(list) {
      this.codeCutSelected = list;
    },
    goBack() {
      window.history.go(-1);
    },
    goBackList() {
      this.$router.push({
        path: "/model/list",
      });
    },
    prev0() {
      window.history.go(-1);
    },
    next0() {
      let self = this;
      if (!this.$common.doSubmit("form", this)) return;
      // this.stepActive = 1;
      switch (this.actionType) {
        case "upload":
          if (!this.$refs.newDataList.submit()) return;
          break;
        case "select":
          if (!this.$refs.selectDataList.submit()) return;
          break;
      }
      function loadAlgorithmUUID_Event(res) {
        if (res.status === 200) {
          self.algorithmList = res.data;
        } else {
          self.$message.error("获取失败！");
          self.algorithmList = [];
        }
      }
      if (this.$webview2.isWPF) {
        window.chrome.webview.addEventListener("message", (e) => {
          let res = e.data.response;
          // TODO： 定制后台数据处理
          switch (e.data.webInfo.requestId) {
            case this.loadAlgorithmUUID:
              loadAlgorithmUUID_Event(res);
              break;
            default:
              break;
          }
        });
      }
      this.next1();
      // this.stepActive = 1;
    },
    // 代码裁剪的跳转
    async next5() {
      await this.$refs.codeCutForm.validate();
      let paramsList = this.codeCutSelected.map((item) => {
        return {
          name: item.dirName,
          parameters: item.parameters,
          projectId: this.form.id,
          type: 1,
        };
      });
      if (paramsList.length === 0) return (this.stepActive = 2); // 如果没有选中项，则直接跳转到训练模型
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/algoCorpgenerate/saveOrUpdateBatch?type=1`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: paramsList,
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.stepActive = 2;
            } else {
              _self.$message.error(result.msg || "保存失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/algoCorpgenerate/saveOrUpdateBatch?type=1`,
          "post",
          "application/json;charset=UTF-8",
          paramsList,
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.stepActive = 2;
            } else {
              this.$message.error(res.msg || "保存失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("postCodeCutRules", paramsList);
        if (res.data.status === 200) {
          this.stepActive = 2;
        } else {
          this.$message.warning(res.msg || "保存失败");
        }
      }
    },
    prev5() {
      this.stepActive = 0;
    },
    updateProjectType() {},
    prev1() {
      this.stepActive = 1;
    },
    next1() {
      let self = this;
      this.setTrainFormRules();
      let result = {};
      if (this.actionType === "upload") {
        // 文件上传
        result = this.$refs.newDataList && this.$refs.newDataList.submit();
        if (result) {
          this.saveProject(result);
        }
      } else if (this.actionType === "select") {
        // 选择原始数据库
        result =
          this.$refs.selectDataList && this.$refs.selectDataList.submit();
        if (result) {
          this.saveProject(result);
        }
      }
      // this.stepActive = 2;
      function creatModalUUID_Event(res) {
        if (res.status === 200) {
          const data = res.data || {};
          self.form.id = data.id || "";
          if (self.actionType === "upload") {
            self.saveDataAndUpload(result);
          } else if (self.actionType === "select") {
            self.saveData(result);
          }
          self.stepActive = 1;
        } else {
          self.$message.error(res.msg || "保存失败");
        }
      }
      // function saveDataAndUpload_Event(e) {
      //   let res = e.data.response;
      //   // TODO： 定制后台数据处理
      //   if (res.status === 200) {
      //     // this.trainFormData = data;
      //     self.hasSelectFile = true;
      //     self.materialFormData.id = res.data.id;
      //     self.materialFormData.fileName = res.data.fileName;
      //     self.trainFormData.fileId = self.materialFormData.id;
      //     self.trainFormData.fileName = self.materialFormData.fileName;
      //     self.trainFormData.projectId = self.form.id;
      //   } else {
      //     self.$message.error(res.msg || "上传数据集失败");
      //   }
      // }
      if (this.$webview2.isWPF) {
        window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            switch (e.data.webInfo.requestId) {
              case this.creatModalUUID:
                creatModalUUID_Event(res);
                break;
              // case this.saveDataAndUploadUUID:
              //   saveDataAndUpload_Event(e);
              //   break;
              default:
                break;
            }
          },
          { once: true }
        );
      }
    },
    setTrainFormRules() {
      if (["data_predict"].includes(this.form.projectType)) {
        this.trainFormRules.variableName[0].required = true;
      }
      if (["img_classify", "voice_classify"].includes(this.form.projectType)) {
        this.trainFormRules.targetColumn[0].required = true;
      }
    },
    // 创建模型
    async saveProject(dataParams) {
      const params = {
        ...this.form,
      };
      this.loading = true;
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          _self.creatModalUUID = uuid;
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/project`,
                RequestMethod: "post",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: params,
                isStringParam: false,
                requestId: _self.creatModalUUID,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.status === 200) {
                const data = result.data || {};
                _self.form.id = data.id || "";
                if (_self.actionType === "upload") {
                  _self.saveDataAndUpload(dataParams);
                } else if (_self.actionType === "select") {
                  _self.saveData(dataParams);
                }
                _self.stepActive = 1;
              } else {
                _self.$message.error(result.msg || "保存失败");
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          this.creatModalUUID = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/project`,
            "post",
            "application/json;charset=UTF-8",
            params,
            false,
            this.creatModalUUID
          );
          // await window.chrome.webview.addEventListener(
          //   "message",
          //   (e) => {
          //     let res = e.data.response;
          //     // TODO： 定制后台数据处理
          //     if (res.status === 200) {
          //       const data = res.data || {};
          //       this.form.id = data.id || "";
          //       if (this.actionType === "upload") {
          //         this.saveDataAndUpload(dataParams);
          //       } else if (this.actionType === "select") {
          //         this.saveData(dataParams);
          //       }
          //     } else {
          //       this.$message.error("保存失败");
          //     }
          //   },
          //   { once: true }
          // );
        } else {
          const res = await this.$store.dispatch("modelManageProject", params);
          const result = res.data || {};
          if (result.success) {
            const data = result.data || {};
            this.form.id = data.id || "";
            if (this.actionType === "upload") {
              this.saveDataAndUpload(dataParams);
            } else if (this.actionType === "select") {
              this.saveData(dataParams);
            }
            this.stepActive = 1;
          } else {
            this.$message.error(result.msg);
          }
        }
      } catch (e) {
        console.error(e);
      }
      this.loading = false;
    },
    // 上传数据集，下一步
    async saveDataAndUpload(dataParams) {
      let formData = new FormData();
      formData.append("File", dataParams.file.raw);
      formData.append("fileName", dataParams.fileName);
      formData.append("fileDesc", dataParams.fileDesc);
      formData.append("projectId", this.form.id); // 项目模型ID
      formData.append("creater", this.$store.state.userName);
      this.loading = true;
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          // 这里对文件的处理需要转成base64的格式后上传
          let reader = new FileReader();
          let fileData = null;
          reader.readAsDataURL(dataParams.file.raw);
          reader.onload = async (e) => {
            fileData = e.target.result;
            const uuid = _self.$qwebUtil.generateRandomUUID();
            _self.saveDataAndUploadUUID = uuid;
            let sendObject;
            /* eslint-disable-next-line */
            const channel = new QWebChannel(
              window.qt.webChannelTransport,
              async function (channel) {
                sendObject = channel.objects.sendObject;
                // receivedJSON 修改此处发送请求参数
                const receivedJSON = {
                  RequestUrl: `/material-info/save-and-upload`,
                  RequestMethod: "post",
                  ContentType: "application/json;charset=UTF-8",
                  RequestBody: {
                    File: fileData,
                    fileName: dataParams.file.name,
                    fileDesc: dataParams.fileDesc,
                    projectId: _self.form.id,
                    creater: _self.$store.state.userName,
                  },
                  isStringParam: false,
                  requestId: _self.saveDataAndUploadUUID,
                };
                await send();
                await _self.$qwebUtil.receive(sendObject, receivedJSON);
                // console.error('received','/feCanvas/pageList')
              }
            );
            /* eslint-disable-next-line */
            async function send() {
              sendObject.sendMessage.connect(function (data) {
                if (!data) {
                  console.error("No data received.");
                }
                res = JSON.parse(data);
                const result = res.response || {};
                // update the followings
                if (result.success && res.webInfo.requestId == uuid) {
                  _self.hasSelectFile = true;
                  _self.materialFormData.id = result.data.id;
                  _self.materialFormData.fileName = result.data.fileName;
                  _self.trainFormData.fileId = _self.materialFormData.id;
                  _self.trainFormData.fileName =
                    _self.materialFormData.fileName;
                  _self.trainFormData.projectId = _self.form.id;
                } else {
                  _self.$message.error(result.msg || "上传数据集失败");
                }
              });
            }
          };
        } else if (this.$webview2.isWPF) {
          // 这里对文件的处理需要转成base64的格式后上传
          let reader = new FileReader();
          let fileData = null;
          reader.readAsDataURL(dataParams.file.raw);
          reader.onload = async (e) => {
            fileData = e.target.result;
            this.saveDataAndUploadUUID = this.$webview2.generateRandomUUID();
            await this.$webview2.sendWebView2(
              `/material-info/save-and-upload`,
              "post",
              "application/json;charset=UTF-8",
              {
                File: fileData,
                fileName: dataParams.file.name,
                fileDesc: dataParams.fileDesc,
                projectId: this.form.id,
                creater: this.$store.state.userName,
              },
              false,
              this.saveDataAndUploadUUID
            );

            function saveDataAndUpload_Event(e) {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.status === 200) {
                // this.trainFormData = data;
                _self.hasSelectFile = true;
                _self.materialFormData.id = res.data.id;
                _self.materialFormData.fileName = res.data.fileName;
                _self.trainFormData.fileId = _self.materialFormData.id;
                _self.trainFormData.fileName = _self.materialFormData.fileName;
                _self.trainFormData.projectId = _self.form.id;
              } else {
                _self.$message.error(res.msg || "上传数据集失败");
              }
            }
            if (this.$webview2.isWPF) {
              window.chrome.webview.addEventListener(
                "message",
                (e) => {
                  // let res = e.data.response;
                  // TODO： 定制后台数据处理
                  switch (e.data.webInfo.requestId) {
                    case this.saveDataAndUploadUUID:
                      saveDataAndUpload_Event(e);
                      break;
                    default:
                      break;
                  }
                },
                { once: true }
              );
            }
          };
        } else {
          const res = await this.$store.dispatch(
            "modelManageMaterialInfoSaveAndUpload",
            formData
          );
          const result = res.data || {};
          if (result.success) {
            const data = result.data || {};
            // this.trainFormData = data;
            this.hasSelectFile = true;
            this.materialFormData.id = data.id;
            this.materialFormData.fileName = data.fileName;
            this.trainFormData.fileId = this.materialFormData.id;
            this.trainFormData.fileName = this.materialFormData.fileName;
            this.trainFormData.projectId = this.form.id;

            // this.stepActive = 1;
          } else {
            this.$message.error(result.msg || "上传数据集失败");
          }
        }
      } catch (e) {
        console.error(e);
      }
      this.loading = false;
    },
    // 选择数据集，下一步
    async saveData(dataParams) {
      const params = {
        ...dataParams,
        projectId: this.form.id,
      };
      this.loading = true;
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/material-info/save`,
                RequestMethod: "post",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: params,
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                const data = result.data || {};
                _self.hasSelectFile = true;
                _self.materialFormData.id = data.id;
                _self.materialFormData.fileName = data.fileName;
                _self.trainFormData.fileId = _self.materialFormData.id;
                _self.trainFormData.fileName = _self.materialFormData.fileName;
                _self.trainFormData.projectId = _self.form.id;
              } else {
                _self.$message.error(result.msg || "保存失败");
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/material-info/save`,
            "post",
            "application/json;charset=UTF-8",
            params,
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                const data = res.data || {};
                // this.trainFormData = data;
                this.hasSelectFile = true;
                this.materialFormData.id = data.id;
                this.materialFormData.fileName = data.fileName;
                this.trainFormData.fileId = this.materialFormData.id;
                this.trainFormData.fileName = this.materialFormData.fileName;
                this.trainFormData.projectId = this.form.id;
              } else {
                this.$message.error(res.msg || "保存失败");
              }
            },
            { once: true }
          );
        } else {
          const res = await this.$store.dispatch(
            "modelManageMaterialInfoSave",
            params
          );
          const result = res.data || {};
          if (result.success) {
            const data = result.data || {};
            // this.trainFormData = data;
            this.hasSelectFile = true;
            this.materialFormData.id = data.id;
            this.materialFormData.fileName = data.fileName;
            this.trainFormData.fileId = this.materialFormData.id;
            this.trainFormData.fileName = this.materialFormData.fileName;
            this.trainFormData.projectId = this.form.id;
            // this.stepActive = 2;
          } else {
            this.$message.error(result.msg || "上传数据集失败");
          }
        }
      } catch (e) {
        console.error(e);
      }
      this.loading = false;
    },

    // 预览
    setShowViewFile() {
      this.showViewFile = true;
      this.loadViewFile();
    },
    prev2() {
      // this.stepActive = 1;
      this.stepActive = 1;
    },
    next2() {
      if (!this.$common.doSubmit("trainForm", this)) return;
      // this.stepActive = 3;
      this.saveTraining();
    },
    // 发布模型
    async publish() {
      const params = {
        modelId: this.modelData.id,
        creater: this.$store.state.userName,
      };
      this.loading = true;
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: "/publishtask/publish-task-data/publish",
                RequestMethod: "post",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: params,
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                _self.$message.success("发布成功");
                window.history.go(-1);
              } else {
                _self.$message.error("发布失败！:" + result.msg);
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            "/publishtask/publish-task-data/publish",
            "post",
            "application/json;charset=UTF-8",
            params,
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                this.$message.success("发布成功");
                window.history.go(-1);
              } else {
                this.$message.error("发布失败！:" + res.msg);
              }
            },
            { once: true }
          );
        } else {
          const res = await this.$store.dispatch(
            "modelManagePublishtaskPublishTaskDataPublish",
            params
          );
          const result = res.data || {};
          if (result.success) {
            this.$message.success("发布成功");
            window.history.go(-1);
          } else {
            this.$message.error("发布失败！:" + result.msg);
          }
        }
      } catch (e) {
        this.$message.error("发布失败！:" + e);
        console.error(e);
      }
      this.loading = false;
    },
    // 开始训练
    async saveTraining() {
      let trainFormData = _.cloneDeep(this.trainFormData);
      if (!trainFormData.id) {
        trainFormData = _.omit(trainFormData, ["id"]);
      }
      if (_.isArray(trainFormData.variableName)) {
        trainFormData.variableName = trainFormData.variableName.join(",");
      }
      // 无监督默认传0.8
      if (this.form.projectType === "data_unsupervised") {
        trainFormData.proportion = "0.8";
      }
      trainFormData.projectId = this.form.id;
      if (
        trainFormData.taskType === "1" &&
        trainFormData.algorithmName === ""
      ) {
        this.$message.error("请选择算法");
      }

      this.loading = true;
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: "/traininginfo/training-info/create",
                RequestMethod: "post",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: trainFormData,
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                // 如果选了自动，返回数据为数组id，如果不是则为字符串id
                if (Array.isArray(result.data)) {
                  _self.reduceCall(result.data);
                }
              } else {
                _self.$message.error(result.msg);
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            "/traininginfo/training-info/create",
            "post",
            "application/json;charset=UTF-8",
            trainFormData,
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                // 如果选了自动，返回数据为数组id，如果不是则为字符串id
                if (Array.isArray(res.data)) {
                  this.reduceCall(res.data);
                }
              } else {
                this.$message.error(res.msg);
              }
            },
            { once: true }
          );
        } else {
          const res = await this.$store.dispatch(
            "modelManageTraininginfoTrainingInfoCreate",
            trainFormData
          );
          const result = res.data || {};
          if (result.success) {
            // 如果选了自动，返回数据为数组id，如果不是则为字符串id
            if (Array.isArray(result.data)) {
              this.reduceCall(result.data);
              // this.$message.success("操作完成");
              // this.loading = false;
              // window.history.go("-1");
            }
          } else {
            this.$message.error(result.msg);
          }
        }
      } catch (e) {
        console.error(e);
      }
      this.loading = false;
    },

    async startTrain(data) {
      const params = {
        // id: data.id || "",
        id: data || "",
      };
      this.loading = true;
      let res = {};
      let _self = this;
      let promiseResult = new Promise(async function (resolve, reject) {
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/traininginfo/training-info/startTask?id=${params.id}`,
                RequestMethod: "post",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: {},
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                resolve();
              } else {
                _self.apiCount = 0;
                _self.loading = false;
                _self.$message.warning(result.data.msg);
                reject(result.data.msg);
              }
            });
          }
        } else if (_self.$webview2.isWPF) {
          const uuid = _self.$webview2.generateRandomUUID();
          await _self.$webview2.sendWebView2(
            `/traininginfo/training-info/startTask?id=${params.id}`,
            "post",
            "application/json;charset=UTF-8",
            {},
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                resolve();
              } else {
                _self.apiCount = 0;
                _self.loading = false;
                _self.$message.warning(res.data.msg);
                reject(res.data.msg);
              }
            },
            { once: true }
          );
        } else {
          const res = await _self.$store.dispatch(
            "modelManageTraininginfoTrainingInfoStartTask",
            params
          );
          if (res.data.status === 200) {
            resolve();
          } else {
            _self.apiCount = 0;
            _self.loading = false;
            _self.$message.warning(res.data.msg);
            reject(res.data.msg);
          }
        }
      });
      return promiseResult;
    },

    // 递归调用请求
    reduceCall(paramsList) {
      let that = this;
      if (paramsList.length > 0) {
        that.startTrain(paramsList[that.apiCount]).then(function (data) {
          that.apiCount++;
          if (that.apiCount < paramsList.length) {
            that.reduceCall(paramsList);
          } else {
            // 执行链完成后的操作
            that.apiCount = 0;
            that.loading = false;
            that.$message.success("操作完成");
            window.history.go("-1");
          }
        });
      }
    },

    async setMaterialAndTask(record) {
      let materialFormData = null;
      let task = null;
      this.loading = true;
      try {
        materialFormData = await this.loadMaterial();
      } catch (e) {
        console.error(e);
      }
      this.materialFormData = _.assignIn(
        this.materialFormData,
        materialFormData
      );

      try {
        task = await this.loadTask();
      } catch (e) {
        console.error(e);
      }
      if (task && task.variableName) {
        task.variableName = task.variableName.split(",");
      }
      if (!task) {
        task = {};
        task["fileId"] = this.materialFormData.id;
        task["fileName"] = this.materialFormData.fileName;
        task["projectId"] = this.materialFormData.projectId;
      }
      this.trainFormData = _.assignIn(this.trainFormData, task);
      this.hasSelectFile = true;
      const progressRate = record.progressRate || "";
      if (progressRate === "material") {
        this.stepActive = 2;
      }
      if (progressRate === "train") {
        this.stepActive = 2;
      }
      if (progressRate === "publish") {
        this.stepActive = 3;
      }

      // 数据回显
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        _self.loadAlgorithmUUID = uuid;
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/classify/get-algorithm-by-type?projectType=${_self.form.projectType}`,
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {
                // projectType: _self.form.projectType || "",
              },
              isStringParam: true,
              requestId: _self.loadAlgorithmUUID,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.algorithmList = result.data;
            } else {
              _self.$message.error("获取失败！");
              _self.algorithmList = [];
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        // const params = {
        //   projectType: this.form.projectType || "",
        // };
        this.loadAlgorithmUUID = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/classify/get-algorithm-by-type?projectType=${this.form.projectType}`,
          "get",
          "application/json;charset=UTF-8",
          {},
          true,
          this.loadAlgorithmUUID
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (
              res.status === 200 &&
              e.data.webInfo.requestId == this.loadAlgorithmUUID
            ) {
              this.algorithmList = res.data;
            } else {
              this.$message.error("获取失败！");
              this.algorithmList = [];
            }
          },
          { once: true }
        );
      }

      this.loading = false;
    },

    async loadMaterial() {
      const params = {
        projectId: this.form.id || "",
      };
      let value;
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          return new Promise(async (resolve) => {
            const uuid = _self.$qwebUtil.generateRandomUUID();
            let sendObject;
            /* eslint-disable-next-line */
            const channel = new QWebChannel(
              window.qt.webChannelTransport,
              async function (channel) {
                sendObject = channel.objects.sendObject;
                // receivedJSON 修改此处发送请求参数
                const receivedJSON = {
                  RequestUrl: `/material-info/findByProjectId?projectId=${_self.form.id}`,
                  RequestMethod: "post",
                  ContentType: "application/json;charset=UTF-8",
                  RequestBody: {},
                  isStringParam: false,
                  requestId: uuid,
                };
                await send();
                await _self.$qwebUtil.receive(sendObject, receivedJSON);
                // console.error('received','/feCanvas/pageList')
              }
            );
            /* eslint-disable-next-line */
            async function send() {
              sendObject.sendMessage.connect(function (data) {
                if (!data) {
                  console.error("No data received.");
                }
                res = JSON.parse(data);
                const result = res.response || {};
                // update the followings
                if (result.success && res.webInfo.requestId == uuid) {
                  value = result.data;
                  resolve(value);
                } else {
                  _self.$message.error("获取失败！");
                }
              });
            }
          });
        } else if (this.$webview2.isWPF) {
          return new Promise(async (resolve, reject) => {
            const uuid = this.$webview2.generateRandomUUID();
            await this.$webview2.sendWebView2(
              `/material-info/findByProjectId?projectId=${this.form.id}`,
              "post",
              "application/json;charset=UTF-8",
              {},
              false,
              uuid
            );
            await window.chrome.webview.addEventListener(
              "message",
              (e) => {
                let res = e.data.response;
                // TODO： 定制后台数据处理
                if (res.status === 200) {
                  value = res.data;
                  resolve(value);
                } else {
                  this.$message.error("获取失败！");
                }
              },
              { once: true }
            );
          });
        } else {
          const res = await this.$store.dispatch(
            "modelManageMaterialInfoFindByProjectId",
            params
          );
          const result = res.data || {};
          if (result.success) {
            value = result.data;
          } else {
            this.$message.error("获取失败！");
          }
        }
      } catch (e) {
        console.error(e);
      }
      return value;
    },

    async loadTask() {
      const params = {
        projectId: this.form.id || "",
      };
      let value;
      this.loading = true;
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          return new Promise((resolve) => {
            setTimeout(async () => {
              const uuid = _self.$qwebUtil.generateRandomUUID();
              let sendObject;
              /* eslint-disable-next-line */
              const channel = new QWebChannel(
                window.qt.webChannelTransport,
                async function (channel) {
                  sendObject = channel.objects.sendObject;
                  // receivedJSON 修改此处发送请求参数
                  const receivedJSON = {
                    RequestUrl: `/traininginfo/training-info/getByProjectId?projectId=${_self.form.id}`,
                    RequestMethod: "get",
                    ContentType: "application/json;charset=UTF-8",
                    RequestBody: {},
                    isStringParam: false,
                    requestId: uuid,
                  };
                  await send();
                  await _self.$qwebUtil.receive(sendObject, receivedJSON);
                  // console.error('received','/feCanvas/pageList')
                }
              );
              /* eslint-disable-next-line */
              async function send() {
                sendObject.sendMessage.connect(function (data) {
                  if (!data) {
                    console.error("No data received.");
                  }
                  res = JSON.parse(data);
                  const result = res.response || {};
                  // update the followings
                  if (result.success && res.webInfo.requestId == uuid) {
                    value = result.data;
                    _self.loading = false;
                    resolve(value);
                    if (!result) {
                      _self.resultStatus = "default";
                    } else {
                      const errorInformation = JSON.parse(
                        value.errorInformation || "{}"
                      );
                      if (errorInformation.code === 200) {
                        _self.resultStatus = "success";
                      } else {
                        _self.resultStatus = "error";
                        _self.errorMessage = errorInformation.msg;
                      }
                    }
                  } else {
                    _self.$message.error("获取失败！");
                    _self.resultStatus = "default";
                  }
                });
              }
            }, 400);
          });
        } else if (this.$webview2.isWPF) {
          return new Promise((resolve, reject) => {
            setTimeout(async () => {
              const uuid = this.$webview2.generateRandomUUID();
              await this.$webview2.sendWebView2(
                `/traininginfo/training-info/getByProjectId?projectId=${this.form.id}`,
                "get",
                "application/json;charset=UTF-8",
                {},
                false,
                uuid
              );
              await window.chrome.webview.addEventListener(
                "message",
                (e) => {
                  let res = e.data.response;
                  // TODO： 定制后台数据处理
                  if (res.status === 200) {
                    value = res.data;
                    this.loading = false;
                    resolve(value);
                    if (!value) {
                      this.resultStatus = "default";
                    } else {
                      const errorInformation = JSON.parse(
                        value.errorInformation || "{}"
                      );
                      if (errorInformation.code === 200) {
                        this.resultStatus = "success";
                      } else {
                        this.resultStatus = "error";
                        this.errorMessage = errorInformation.msg;
                      }
                    }
                  } else {
                    this.$message.error("获取失败！");
                    this.resultStatus = "default";
                  }
                },
                { once: true }
              );
            }, 400);
          });
        } else {
          const res = await this.$store.dispatch(
            "modelManageTraininginfoTrainingInfoGetByProjectId",
            params
          );
          const result = res.data || {};
          if (result.success) {
            const data = result.data;
            value = data;
            if (!data) {
              this.resultStatus = "default";
            } else {
              const errorInformation = JSON.parse(
                data.errorInformation || "{}"
              );
              if (errorInformation.code === 200) {
                this.resultStatus = "success";
              } else {
                this.resultStatus = "error";
                this.errorMessage = errorInformation.msg;
              }
            }
          } else {
            this.$message.error("获取失败！");
            this.resultStatus = "default";
          }
        }
      } catch (e) {
        console.error(e);
      }
      this.loading = false;
      return value;
    },
    //
    async loadAlgorithm() {
      const params = {
        projectType: this.form.projectType || "",
      };
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          _self.loadAlgorithmUUID = uuid;
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/classify/get-algorithm-by-type?projectType=${_self.form.projectType}`,
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: {},
                isStringParam: true,
                requestId: _self.loadAlgorithmUUID,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // TODO： 定制后台数据处理
              if (result.success && res.webInfo.requestId == uuid) {
                _self.algorithmList = result.data;
              } else {
                _self.$message.error("获取失败！");
                _self.algorithmList = [];
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          this.loadAlgorithmUUID = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/classify/get-algorithm-by-type?projectType=${this.form.projectType}`,
            "get",
            "application/json;charset=UTF-8",
            {},
            true,
            this.loadAlgorithmUUID
          );
          //   await window.chrome.webview.addEventListener(
          //     "message",
          //     (e) => {
          //       let res = e.data.response;
          //       // TODO： 定制后台数据处理
          //       if (res.status === 200) {
          //         this.algorithmList = res.data;
          //       } else {
          //         this.$message.error("获取失败！");
          //         this.algorithmList = [];
          //       }
          //     },
          //     { once: true }
          //   );
        } else {
          const res = await this.$store.dispatch(
            "modelManageClassifyGetAlgorithmByType",
            params
          );
          const result = res.data || {};
          if (result.success) {
            this.algorithmList = result.data;
            //  获得算法模型
          } else {
            this.$message.error("获取失败！");
            this.algorithmList = [];
          }
        }
      } catch (e) {
        console.error(e);
      }
    },
    // 在线数据预览查询
    async loadViewFile() {
      const params = {
        fileId: this.materialFormData.id,
        encoding: "UTF-8",
      };
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/material-info/viewfile`,
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: params,
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                const viewFile = result.data || [];
                if (viewFile.length > 0) {
                  _self.variableList = viewFile[0];
                  _self.targetList = viewFile[0];
                } else {
                  _self.variableList = [];
                  _self.targetList = [];
                }
                _self.viewFile = viewFile;
              } else {
                _self.$message.error("获取失败！");
                _self.resultStatus = "default";
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/material-info/viewfile`,
            "get",
            "application/json;charset=UTF-8",
            params,
            false,
            uuid
          );

          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.status === 200) {
                const viewFile = res.data || [];
                if (viewFile.length > 0) {
                  this.variableList = viewFile[0];
                  this.targetList = viewFile[0];
                } else {
                  this.variableList = [];
                  this.targetList = [];
                }
                this.viewFile = viewFile;
              } else {
                this.$message.error("获取失败！");
                this.resultStatus = "default";
              }
            },
            { once: true }
          );
        } else {
          const res = await this.$store.dispatch(
            "modelManageMaterialInfoViewFile",
            params
          );
          const result = res.data || {};
          if (result.success) {
            const viewFile = result.data || [];
            if (viewFile.length > 0) {
              this.variableList = viewFile[0];
              this.targetList = viewFile[0];
            } else {
              this.variableList = [];
              this.targetList = [];
            }
            this.viewFile = viewFile;
          } else {
            this.$message.error("获取预览数据报错:" + result.msg);
          }
        }
      } catch (e) {
        console.error(e);
      }
    },

    async loadModelResults() {
      let taskId = "";
      try {
        let task = await this.loadTask();
        if (task) {
          taskId = task.id;
        }
      } catch (e) {
        console.error(e);
      }
      let modelData = {};
      try {
        modelData = await this.getModelData(taskId);
      } catch (err) {
        return;
      }
      let evaluate = eval("(" + modelData.evaluate + ")"),
        result = [];
      evaluate = _.forIn(evaluate, (value, key) => {
        let obj = {
          name: key,
          ...value,
        };
        result.push(obj);
      });
      this.modelData = modelData;
      this.modelResults = result;

      // 如果数据训练集或测试集中的准确度低于0.3，则修改训练状态为失败
      let isLowAccuracy = this.modelResults.filter((item) => {
        if (item.accuracy < 0.3) {
          return true;
        }
      });
      if (isLowAccuracy.length > 0) {
        this.successMessage = "准确率过低！";
        return;
      }
    },

    async getModelData(taskId) {
      const params = {
        taskId: taskId,
      };
      let value;
      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          return new Promise(async (resolve) => {
            const uuid = _self.$qwebUtil.generateRandomUUID();
            let sendObject;
            /* eslint-disable-next-line */
            const channel = new QWebChannel(
              window.qt.webChannelTransport,
              async function (channel) {
                sendObject = channel.objects.sendObject;
                // receivedJSON 修改此处发送请求参数
                const receivedJSON = {
                  RequestUrl: `/training-model-data/find-by-training-task/${params.taskId}`,
                  RequestMethod: "get",
                  ContentType: "application/json;charset=UTF-8",
                  RequestBody: {},
                  isStringParam: false,
                  requestId: uuid,
                };
                await send();
                await _self.$qwebUtil.receive(sendObject, receivedJSON);
                // console.error('received','/feCanvas/pageList')
              }
            );
            /* eslint-disable-next-line */
            async function send() {
              sendObject.sendMessage.connect(function (data) {
                if (!data) {
                  console.error("No data received.");
                }
                res = JSON.parse(data);
                const result = res.response || {};
                // update the followings
                if (result.success && res.webInfo.requestId == uuid) {
                  value = result.data || {};
                  resolve(value);
                } else {
                  _self.$message.error("获取失败！");
                }
              });
            }
          });
        } else if (this.$webview2.isWPF) {
          return new Promise(async (resolve, reject) => {
            const uuid = this.$webview2.generateRandomUUID();
            await this.$webview2.sendWebView2(
              `/training-model-data/find-by-training-task/${params.taskId}`,
              "get",
              "application/json;charset=UTF-8",
              {},
              false,
              uuid
            );
            await window.chrome.webview.addEventListener(
              "message",
              (e) => {
                let res = e.data.response;
                // TODO： 定制后台数据处理
                if (res.status === 200) {
                  value = res.data || {};
                  resolve(value);
                } else {
                  this.$message.error("获取失败！");
                }
              },
              { once: true }
            );
          });
        } else {
          const res = await this.$store.dispatch(
            "modelManageTrainingModelDataFindByTrainingTask",
            params
          );
          const result = res.data || {};
          if (result.success) {
            value = result.data || {};
          } else {
            this.$message.error("获取失败！");
          }
        }
      } catch (e) {
        console.error(e);
      }
      return value;
    },

    changeAlgorithm(value) {
      let algorithmSelect = _.cloneDeep(this.algorithmSelect);
      let re = _.find(algorithmSelect, { algorithmName: value })
        ? _.find(algorithmSelect, { algorithmName: value }).algorithmType
        : "";
      this.trainFormData.type = re;
    },
    changeAlgorithmClass(value) {
      let algorithmSelect = _.cloneDeep(this.algorithmSelect);
      this.trainFormData.type = algorithmSelect[0].algorithmType;
    },

    // 算法参数-设置默认参数
    setDefaultParameter() {
      if (this.algorithmList.length) {
        const { algorithmClass, algorithmName } = this.trainFormData;
        if (algorithmClass && algorithmName) {
          const target = this.algorithmList.find(
            (item) =>
              item.algorithmClass === algorithmClass &&
              item.algorithmName === algorithmName
          );
          if (target) {
            const parameter = target.parameter;
            this.trainFormData.extraParam = parameter
              ? JSON.stringify(JSON.parse(parameter), null, 2)
              : "";
            // this.parameter = parameter ? JSON.stringify(JSON.parse(parameter), null, 2) : '';
          } else {
            this.trainFormData.extraParam = "";
            // this.parameter = '';
          }
        } else {
          this.trainFormData.extraParam = "";
          // this.parameter = '';
        }
      } else {
        this.trainFormData.extraParam = "";
        // this.parameter = '';
      }
    },

    validateTarget(rule, value, callback) {
      let variableNameList = this.trainFormData.variableName;
      if (variableNameList.length === 0) {
        callback();
      }
      let re = true;
      for (let i = 0, length = variableNameList.length; i < length; i++) {
        if (value === variableNameList[i]) {
          re = false;
        }
      }
      if (!re) {
        callback(new Error("标签列值不能为自变量值中的一员"));
      }

      callback();
    },

    // 校验算法参数
    checkExtraParam(rule, value, callback) {
      if (!value) {
        callback(new Error("请输入算法参数"));
      } else {
        const flag = isJSON(value);
        if (!flag) {
          callback(new Error("请输入JSON格式的算法参数"));
        } else {
          callback();
        }
      }
    },
    statusUnpublish(row = {}) {
      return row.status === "unpublish";
    },
    async getModelTableData() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/dictionary/TreeList?dirCodes=model_`,
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {},
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              //   默认赋值下拉选项的第一个
              result.data.forEach((item) => {
                item.parameters = item.childrenParams[0].optName;
              });
              _self.codeCutform.tableData = result.data;
              // _self.$set(_self.codeCutform, "tableData", result.data);
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/dictionary/TreeList?dirCodes=model_`,
          "get",
          "application/json;charset=UTF-8",
          {},
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200) {
              //   默认赋值下拉选项的第一个
              res.data.forEach((item) => {
                item.parameters = item.childrenParams[0].optName;
              });
              // this.$set(this.codeCutform, "tableData", res.data);
              this.codeCutform.tableData = res.data;
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getDicBydirCode", {
          dirCodes: "model_",
        });
        if (res.data.status === 200) {
          //   默认赋值下拉选项的第一个
          res.data.data.forEach((item) => {
            item.parameters = item.childrenParams[0].optName;
          });
          // this.$set(this.codeCutform, "tableData", res.data.data);
          this.codeCutform.tableData = res.data.data;
        }
      }
    },
  },
  mounted() {
    // 获取代码裁剪中model_下拉选项
    // setTimeout(() => {
    //   this.getModelTableData();
    // }, 200);
    // 设置面包屑导航
    this.$store.commit("SET_BREADCRUMB", [
      { title: "前沿算法诊断", path: "/model/list" },
      { title: "新建前沿算法", path: "" },
    ]);

    let params = this.$router.currentRoute.params;
    if (params.data) {
      const record = params.data;
      this.$store.commit("SET_BREADCRUMB", [
        { title: "前沿算法诊断", path: "/model/list" },
        { title: "模型详情", path: `/model/detail?id=${record.id}` },
        { title: "新建前沿算法", path: "" },
      ]);
      const projectType = record.projectType || "";
      this.form = {
        id: record.id,
        creater: this.$store.state.userName,
        projectName: record.projectName,
        projectDesc: record.projectDesc,
        projectType: record.projectType,
        isAvailable: record.isAvailable,
      };
      this.setTrainFormRules();
      if (params.isToModelResult) {
        console.log("isToModelResult");
        this.stepActive = 3;
        setTimeout(() => {
          this.loadModelResults();
        }, 400);
      } else {
        console.log("isNotToModelResult");
        setTimeout(() => {
          this.setMaterialAndTask(record);
        }, 400);
      }
    }
  },
};
</script>
<style lang="less" scoped>
@import url("~@/style/variables.less");

.form-wrapper {
  width: 800px;
}

.steps {
  padding-top: 16px;
  padding-bottom: 56px;
}

.actionType {
  display: block;
  text-align: center;
  margin-bottom: 28px;
}

.el-select {
  width: 100%;
}

.progress-item {
  text-align: center;

  &.is-success {
    .progress-text {
      color: #52bb26;
    }
  }

  &.is-error {
    .progress-text {
      color: #f73d47;
    }
  }

  /deep/ i {
    font-size: 32px;
    font-weight: bold;
  }
}

.progress-text {
  font-family: PingFangSC-Medium;
  font-size: 20px;
  font-weight: 500;
}

.progress-tips {
  font-family: PingFangSC-Regular;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  line-height: 22px;
  font-weight: 400;
}

/deep/ .el-form-item__content .el-input-group {
  vertical-align: middle;
}

.data-set {
  width: 246px;
  height: 90px;
  background: #ffffff;
  border: 1px solid rgba(0, 0, 0, 0.06);
  box-shadow: 0px 6px 16px -8px rgba(0, 0, 0, 0.08);
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  display: flex;
  padding: 13px 16px;
  box-sizing: border-box;

  .data-set-title {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: @--color-text-primary;
    line-height: 22px;
    font-weight: 400;
  }

  img {
    width: 34px;
    margin-right: 21px;
  }
}
/deep/ .el-table td {
  padding: 4px 0;
}
/deep/ .el-table {
  margin-bottom: 10px;
}
/deep/ .el-table__row .el-form-item {
  margin-bottom: 0px;
}
</style>
